package cre.tomcat.ch13.startup;

import cre.tomcat.ch10.core.SimpleContextConfig;
import org.apache.catalina.*;
import org.apache.catalina.connector.http.HttpConnector;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.core.StandardHost;
import org.apache.catalina.core.StandardWrapper;
import org.apache.catalina.loader.WebappClassLoader;
import org.apache.catalina.loader.WebappLoader;
import org.apache.naming.resources.ProxyDirContext;

import static cre.tomcat.common.Constants.CATALINA_BASE;

/**
 * 安全性
 * tomcat bootstrap
 *
 * @Author penglai
 * @Date 2017/1/4.
 */
public class Bootstrap1 {

    public static void main(String[] args) {
        //invoke: http://localhost:8080/app1/Primitive or http://localhost:8080/app1/Modern
        System.setProperty("catalina.base", CATALINA_BASE);
        Connector connector = new HttpConnector();

        Wrapper wrapper1 = new StandardWrapper();
        wrapper1.setName("Primitive");
        wrapper1.setServletClass("PrimitiveServlet");

        Wrapper wrapper2 = new StandardWrapper();
        wrapper2.setName("Modern");
        wrapper2.setServletClass("ModernServlet");

        Context context = new StandardContext();
        context.setPath("/app1");
        context.setDocBase("app1");

        context.addChild(wrapper1);
        context.addChild(wrapper2);
        context.addServletMapping("/Primitive", "Primitive");
        context.addServletMapping("/Modern", "Modern");

        Loader loader = new WebappLoader();
        context.setLoader(loader);

        LifecycleListener lifecycleListener = new SimpleContextConfig();
        ((Lifecycle) context).addLifecycleListener(lifecycleListener);

        Host host = new StandardHost();
        host.setName("localhost");
        host.setAppBase("host-webapps");
        host.addChild(context);

        connector.setContainer(host);
        try {
            connector.initialize();
            ((Lifecycle) connector).start();
            ((Lifecycle) host).start();

            printResource(context.getLoader());
            System.in.read();
            ((Lifecycle) host).stop();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void printResource(Loader loader) {
        WebappClassLoader classLoader = (WebappClassLoader) loader.getClassLoader();
        System.out.println("Resources's docBase: " + ((ProxyDirContext) classLoader.getResources()).getDocBase());

        String[] repositories = classLoader.findRepositories();
        for (String repository : repositories) {
            System.out.println(" repository: " + repository);
        }
    }
}
